package jee.demo.pro.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

/**
 * Created by Zhen on 2015/4/18.
 */
public class MySQLUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(MySQLUtil.class);

    public static void shutdown() {
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        Driver d = null;
        while (drivers.hasMoreElements()) {
            try {
                d = drivers.nextElement();
                DriverManager.deregisterDriver(d);
                LOGGER.info(String.format("Driver %s deregistered", d));
            } catch (SQLException ex) {
                LOGGER.warn(String.format("Error deregistering driver %s", d), ex);
            }
        }
        try {
            Class<?> cls = Class.forName("com.mysql.jdbc.AbandonedConnectionCleanupThread");
            Method method = (cls == null ? null : cls.getMethod("shutdown"));
            if (method != null) {
                LOGGER.info("MySQL connection cleanup thread shutdown");
                method.invoke(null);
                LOGGER.info("MySQL connection cleanup thread shutdown successfully");
            }
        } catch (Throwable thr) {
            LOGGER.error("Failed to shutdown SQL connection cleanup thread: " + thr.getMessage());
            thr.printStackTrace();
        }
    }
}
